package com.cby.widget.sample;

import android.text.TextUtils;
import android.util.Log;

import androidx.fragment.app.Fragment;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Map;

/**
 * @author ChenBaoyang
 * @description: HykbDialogFragmentFactory
 * @date 2021/9/1 09:46
 */
public class FragmentFactory {

    private static final String TAG = FragmentFactory.class.getSimpleName();

    private static Map<String, String> sFragmentAdMap = new HashMap<>();

    static {
        //sFragmentAdMap.put(TAG_FRAGMENT_CODE, HykbCheckCodeDialogFragment.class.getName());
        //sFragmentAdMap.put(TAG_FRAGMENT_UPDATE, HykbUpdateDialogFragment.class.getName());
        //sFragmentAdMap.put(TAG_FRAGMENT_TIP, HykbTipDialogFragment.class.getName());
    }

    private FragmentFactory() {}

    public static FragmentFactory getInstance() {
        return Inner.INSTANCE;
    }


    /**
     * 通过反射获取DialogFragment对象
     *
     * @param tag
     * @return
     */
    public Fragment createFragment(String tag) {

        if (TextUtils.isEmpty(tag)) {
            return null;
        }

        Fragment api = null;
        try {
            String channelClassName = sFragmentAdMap.get(tag);
            api = internalCreate(channelClassName, Fragment.class);
            Log.i(TAG, "instantiate success");
        } catch (Exception e) {
            Log.e(TAG, "instantiate failed," + e.getMessage());
        }

        return api;
    }

    /**
     * 通过反射方式创建实例
     *
     * @throws Exception
     */
    protected Fragment internalCreate(String className,
                                      Class<Fragment> apiClass)
            throws Exception {

        Class<? extends Fragment> clazz = Class.forName(className)
                .asSubclass(apiClass);

        Constructor<?> clazzConstructor = clazz.getDeclaredConstructor(
                (Class[]) null);
        clazzConstructor.setAccessible(true);
        return (Fragment) clazzConstructor.newInstance();
    }

    private static class Inner {
        public static final FragmentFactory INSTANCE = new FragmentFactory();
    }
}
